//
//  OrderSumupViewController.swift
//  miaoyin
//
//  Created by David on 2017/3/7.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit
import CoreLocation

class OrderSumupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PayViewDelegate {
    
    var step0VC: UIViewController?
    
    var shopInfos: NSDictionary!
    var fileInfos: NSArray!
    
    var tableView: UITableView!
    
    var bottomBar: UIView! // 底部栏
    var totalPriceLabel: UILabel! // 合计label
    var submitBtn: UIButton! // 提交订单按钮
    
    var spinner: UIView!
    var actIndi: UIActivityIndicatorView!
    
    var totalPrice: Double = 0.0
    
    var shopDescriptionHeight:CGFloat = 72.0 //商家详细描述的高度
    
    var commentInput:UITextField! // 备注输入框
    
    var pricesTabel: NSDictionary?
    
    var allDescribe = ""
    
    var phoneInput: UITextField!
    var nameInput: UITextField!
    
    var hasUnsupportedItems = false
    
    var payView: PayView!
    
    convenience init(files: NSArray, shopInfo: NSDictionary?){
        self.init()
        fileInfos = files
        shopInfos = shopInfo
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "提交订单"
        
        // MARK: 备注输入框
        commentInput = UITextField(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
        commentInput.tag = 101
        commentInput.placeholder = "留下你的备注，比如装订等等"
        commentInput.addTarget(self, action: #selector(OrderSumupViewController.textFieldScrollUp(_:)), for: .editingDidBegin)
        
        tableView = UITableView(frame: view.frame, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.allowsSelection = false
        tableView.keyboardDismissMode = .onDrag
        view.addSubview(tableView)
        
        
        
        // MARK: 底部栏
        bottomBar = UIView(frame: CGRect(x: -0.5, y: view.bounds.height - 48, width: view.bounds.width+1, height: 48))
        bottomBar.backgroundColor = UIColor.white
        bottomBar.layer.borderColor = UIColor.lightGray.cgColor
        bottomBar.layer.borderWidth = 0.5
        view.addSubview(bottomBar)
        
        // MARK: 底部显示合计
        totalPriceLabel = UILabel(frame: CGRect(x: 16, y: 8, width: 120, height: 32))
        totalPriceLabel.font = UIFont.systemFont(ofSize: 12)
        bottomBar.addSubview(totalPriceLabel)
        
        //MARK: 计算合计
        /*
        let pricesModel = shopInfos.object(forKey: "price") as? NSDictionary
        let prices = NSMutableDictionary()
        if pricesModel != nil{
            for item in pricesModel!.allValues{
                let priceItem = item as! NSDictionary
                let paperSize = priceItem.object(forKey: "paper_type") as? String
                let paperPrice = priceItem.object(forKey: "price") as? String
                
                prices.setValue(paperPrice, forKey: paperSize!)
                
            }
        }
        
        print(prices)
        pricesTabel = NSDictionary(dictionary: prices)
        
        
        // MAR: 获取价目
        var singleBW:Double?
        let singleBWStr = prices.object(forKey: "1")
        if singleBWStr != nil{
            allDescribe += "单面黑白: ￥\(singleBWStr as? String ?? "")  "
            singleBW = Double(singleBWStr as? String ?? "")
        }
        var duplexBW:Double?
        let duplexBWStr = prices.object(forKey: "2")
        if duplexBWStr != nil{
            allDescribe += "双面黑白: ￥\(duplexBWStr as? String ?? "")  "
            duplexBW = Double(duplexBWStr as? String ?? "")
        }
        var singleColor:Double?
        let singleColorStr = prices.object(forKey: "3")
        if singleColorStr != nil{
            allDescribe += "单面彩色: ￥\(singleColorStr as? String ?? "")  "
            singleColor = Double(singleColorStr as? String  ?? "")
        }
        
        var duplexColor:Double?
        let duplexColorStr = prices.object(forKey: "4")
        if duplexColorStr != nil{
            allDescribe += "双面彩色: ￥\(duplexColorStr as? String ?? "")  "
            duplexColor = Double(duplexColorStr as? String  ?? "") 
        }
        
        if describe != nil{
            allDescribe += "\n\(describe!)"
        }
        
        shopDescriptionHeight = allDescribe.boundingRect(with: CGSize(width: view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil).height
        
        totalPrice = 0.0
        for item in fileInfos{
            let fileItem = item as? NSDictionary
            let pageNum = fileItem?.object(forKey: "page_number") as? Int
            let quantity = fileItem?.object(forKey: "goods_number") as? Int
            
            
            let bwOption = fileItem?.object(forKey: "black_white_color") as? Int
            let duplex = fileItem?.object(forKey: "single_double") as? Int
            
            if pageNum != nil && quantity != nil{
                if duplex == 1 && bwOption == 1{
                    if singleBW != nil{
                        totalPrice += Double(pageNum!*quantity!)*singleBW!
                    }
                }else if duplex == 1 && bwOption == 2{
                    if singleColor != nil{
                        totalPrice += Double(pageNum!*quantity!)*singleColor!
                    }
                }else if duplex == 2 && bwOption == 1{
                    if duplexBW != nil{
                        totalPrice += Double(pageNum!*quantity!)*duplexBW!
                    }
                }else if duplex == 2 && bwOption == 2{
                    if duplexColor != nil{
                        totalPrice += Double(pageNum!*quantity!)*duplexColor!
                    }
                }
            }
            
            
        }
        let showStr = "合计: ￥\(String(format: "%.2lf", totalPrice))"
        let attrStr = NSMutableAttributedString(string: showStr)
        if Int(totalPrice*100) != 0{
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(4, attrStr.length - 4))
        }
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 16), range: NSMakeRange(5, attrStr.length - 5))
        
        totalPriceLabel.attributedText = attrStr
        */
        
        // MARK:提交按钮
        submitBtn = UIButton(frame: CGRect(x: view.bounds.width - 119, y: 0, width: 120, height: 48))
        submitBtn.backgroundColor = UIColor.lightGray
        submitBtn.setTitle("下一步", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        bottomBar.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(OrderSumupViewController.nextStep), for: .touchUpInside)
        submitBtn.isEnabled = false
        
        
        //菊花
        spinner = UIView(frame: view.frame)
        let actIndiBG = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        actIndiBG.center = view.center
        actIndiBG.backgroundColor = UIColor(white: 0, alpha: 0.7)
        actIndiBG.layer.cornerRadius = 8
        spinner.addSubview(actIndiBG)
        actIndi = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        actIndi.startAnimating()
        actIndi.center = view.center
        spinner.addSubview(actIndi)
        view.addSubview(spinner)
        
        spinner.alpha = 0
        
        
        nameInput = UITextField(frame: CGRect(x: 16, y: 8, width: 100, height: 28))
        nameInput.placeholder = "姓名"
        nameInput.tag = 102
        
        phoneInput = UITextField(frame: CGRect(x: 124, y: 8, width: view.bounds.width - 124 - 16, height: 28))
        phoneInput.placeholder = "联系电话"
        phoneInput.keyboardType = .phonePad
        phoneInput.textAlignment = .right
        phoneInput.tag = 104
        
        // MARK: 获取用户手机号
        if UserDefaults.standard.object(forKey: "info_name") != nil{
            nameInput.text = UserDefaults.standard.object(forKey: "info_name") as? String
        }
        
        if UserDefaults.standard.object(forKey: "info_phone") != nil {
            phoneInput.text = UserDefaults.standard.object(forKey: "info_phone") as? String
        }
        
        let shopItem = shopInfos!//shopInfos.object(at: 0) as! NSDictionary
        let describe = shopItem.object(forKey: "description") as? String
        let address = shopItem.object(forKey: "location") as? String
        let phone = shopItem.object(forKey: "phone") as? String
        let startTime = shopItem.object(forKey: "start") as? String
        let endTime = shopItem.object(forKey: "end") as? String
        
        
        
        if address != nil {
            var glAddress = "地址: \(address!)\n"
            let compo = address!.components(separatedBy: ",")
            if compo.count > 1 {
                let lon = Double(compo[0])
                let lat = Double(compo[1])
                if lon != nil && lat != nil{
                    CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: lat!, longitude: lon!), completionHandler: { (plm, err) in
                        if plm != nil{
                            let place = plm?.first
                            if place != nil{
                                print(place?.addressDictionary ?? "nil")
                                glAddress = "地址: \((place?.addressDictionary?["FormattedAddressLines"] as? NSArray)?.object(at: 0) as? String ?? "")\n"
                            }
                        }
                        self.allDescribe += glAddress
                        if phone != nil{
                            self.allDescribe += "电话: \(phone!)\n"
                        }
                        if startTime != nil && endTime != nil{
                            self.allDescribe += "营业时间: \(startTime!)~\(endTime!)\n"
                        }else if startTime != nil{
                            self.allDescribe += "营业时间: \(startTime!)开始\n"
                        }else if endTime != nil{
                            self.allDescribe += "营业时间: \(endTime!)打烊\n"
                        }
                        
                        if describe != nil{
                            self.allDescribe += "\n\(describe!)"
                        }
                        self.checkOrder()
                        
                    })
                }
                
            }
            
        }
        
        
        
        
        payView = PayView(frame: view.frame)
        payView.delegate = self
        view.addSubview(payView)
    }
    /*
    func getGoodsInfo(){
        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=business&a=businessGoods")!)
        resq.httpMethod = "POST"
        let code = shopInfos.object(forKey: "code") as? String
        if code != nil{
            resq.httpBody = "code=\(code!)".data(using: .utf8)
            
            URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                do{
                    if er != nil{
                        throw er!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    self.pricesTabel = jsonData
                    let bsingle = jsonData?.object(forKey: "bsingle") as? String
                    let csingle = jsonData?.object(forKey: "csingle") as? String
                    let bdouble = jsonData?.object(forKey: "bdouble") as? String
                    let cdouble = jsonData?.object(forKey: "cdouble") as? String
                    
                    var priceBoard = ""
                    if bsingle != nil{
                        priceBoard += "黑白单面: ￥\(bsingle!)"
                    }
                    if csingle != nil{
                        if priceBoard.characters.count != 0{
                            priceBoard += ", "
                        }
                        priceBoard += "彩色单面: ￥\(csingle!)"
                    }
                    if bdouble != nil{
                        if priceBoard.characters.count != 0{
                            priceBoard += ", "
                        }
                        priceBoard += "黑白双面: ￥\(bdouble!)"
                    }
                    if cdouble != nil{
                        if priceBoard.characters.count != 0{
                            priceBoard += ", "
                        }
                        priceBoard += "彩色双面: ￥\(cdouble!)"
                    }
                    
                    self.allDescribe += priceBoard
                    
                    self.shopDescriptionHeight = (self.allDescribe as NSString).boundingRect(with: CGSize(width: self.view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 14)], context: nil).height
                    
                    // MARK:合计
                    self.totalPrice = 0.0
                    for item in self.fileInfos{
                        let fileItem = item as? NSDictionary
                        //["file": printView.file!, "paperOption": printView.paperOption, "goods_number":printView.quantity]
                        let paperOption = fileItem?.object(forKey: "paperOption") as? FCPrintPaperType ?? .blackWhiteSingle
                        let pageNum = (fileItem?.object(forKey: "file") as? FCPrintFile)?.filePage ?? "0"
                        let goodNum = fileItem?.object(forKey: "goods_number") as? Int ?? 0
                        
                        switch paperOption{
                        case .blackWhiteSingle:
                            self.totalPrice += (Double(bsingle ?? "0") ?? 0.0)*(Double(pageNum) ?? 0.0)*(Double(goodNum))
                            if bsingle == nil{
                                self.hasUnsupportedItems = true
                            }
                            break
                        case .blackWhiteDouble:
                            self.totalPrice += (Double(bdouble ?? "0") ?? 0.0)*(Double(pageNum) ?? 0.0)*(Double(goodNum))
                            if bdouble == nil{
                                self.hasUnsupportedItems = true
                            }
                            break
                        case .colorSingle:
                            self.totalPrice += (Double(csingle ?? "0") ?? 0.0)*(Double(pageNum) ?? 0.0)*(Double(goodNum))
                            if csingle == nil{
                                self.hasUnsupportedItems = true
                            }
                            break
                        case .colorDouble:
                            self.totalPrice += (Double(cdouble ?? "0") ?? 0.0)*(Double(pageNum) ?? 0.0)*(Double(goodNum))
                            if cdouble == nil{
                                self.hasUnsupportedItems = true
                            }
                            break
                        }
                        
                    }
                    let showStr = "合计: ￥\(String(format: "%.2lf", self.totalPrice))"
                    let attrStr = NSMutableAttributedString(string: showStr)
                    if Int(self.totalPrice*100) != 0{
                        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(4, attrStr.length - 4))
                    }
                    
                    attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 16), range: NSMakeRange(5, attrStr.length - 5))
                    
                    
                    
                    
                    DispatchQueue.main.async {
                        self.totalPriceLabel.attributedText = attrStr
                        self.tableView.reloadData()
                        self.submitBtn.backgroundColor = themeColor1
                        self.submitBtn.isEnabled = true
                    }
                    
                }catch let ex{
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(ex)
                }
            }).resume()
            
        }else{
            let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
        
        
    }
    */
    
    func checkOrder(){
        var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=checkOrder")!)
        req.httpMethod = "POST"
        
        let fileItem = fileInfos.firstObject as? NSDictionary
        
        let printType = fileItem?.object(forKey: "paperOption") as? FCPrintPaperType ?? .blackWhiteSingle
        
        var paperOption = "bsingle"
        switch printType {
        case .blackWhiteSingle:
            paperOption = "bsingle"
            break
        case .blackWhiteDouble:
            paperOption = "bdouble"
            break
        case .colorSingle:
            paperOption = "csingle"
            break
        case .colorDouble:
            paperOption = "cdouble"
            break
        }
        print(shopInfos)
        req.httpBody = "bid=\(shopInfos.object(forKey: "id") as? String ?? "")&itemid=\((fileItem?.object(forKey: "file") as? FCPrintFile)?.fileID ?? "")&type=\(paperOption)&num=\(fileItem?.object(forKey: "goods_number") as? Int ?? 0)".data(using: .utf8)
        URLSession.shared.dataTask(with: req) { (data, _, err) in
            do{
                if err != nil{
                    throw err!
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                self.pricesTabel = jsonData
                
                var tPrice = Double(jsonData?.object(forKey: "total_price") as? String ?? "")
                if tPrice == nil{
                    tPrice = jsonData?.object(forKey: "totalPrice") as? Double
                }
                self.totalPrice = tPrice ?? 0.0
                
                let showStr = "合计: ￥\(String(format: "%.2lf", self.totalPrice))"
                let attrStr = NSMutableAttributedString(string: showStr)
                if Int(self.totalPrice*100) != 0{
                    attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(4, attrStr.length - 4))
                }
                
                attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 16), range: NSMakeRange(5, attrStr.length - 5))
                
                self.shopDescriptionHeight = (self.allDescribe as NSString).boundingRect(with: CGSize(width: self.view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 14)], context: nil).height
                
                DispatchQueue.main.async {
                    self.totalPriceLabel.attributedText = attrStr
                    self.tableView.reloadData()
                    if Int(self.totalPrice*100) != 0{
                        self.submitBtn.backgroundColor = themeColor1
                        self.submitBtn.isEnabled = true
                    }
                    
                }
                
            }catch let ex{
                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                print(ex)
            }
        }.resume()
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3 // 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 2: // 3:
            return fileInfos.count*2
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
//        case 1:
//            return "您的信息"
        case 1: // 2:
            return "备注"
        case 2: // 3:
            return "合计"
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.001
        }
        return 16
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                return 44
            case 1:
                return shopDescriptionHeight + 16 // 动态调整
            default:
                return 44
            }
        case 2: // 3:
            return 30
        default:
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        let shopItem = shopInfos!//.object(at: 0) as! NSDictionary
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
                icon.backgroundColor = UIColor.gray
                cell.addSubview(icon)
                
                let namLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 60, height: 28))
                namLabel.text = shopItem.object(forKey: "nickname") as? String
                cell.addSubview(namLabel)
                
                let shopImage = shopItem.object(forKey: "logo") as? String
                if shopImage != nil{
                    let imageURL = URL(string: shopImage!)
                    if imageURL != nil{
                        URLSession.shared.dataTask(with: imageURL!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                            if err == nil{
                                if data != nil{
                                    let image = UIImage(data: data!)
                                    DispatchQueue.main.async {
                                        icon.image = image
                                    }
                                }
                            }
                        }).resume()
                    }
                }
                break
            case 1:
                
                // MARK: 加一行 显示营业时间
                let describeLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: shopDescriptionHeight))
                describeLabel.textColor = UIColor.gray
                describeLabel.font = UIFont.systemFont(ofSize: 14)
                describeLabel.numberOfLines = 0
                cell.addSubview(describeLabel)
                
                describeLabel.text = allDescribe
                break
            default:
                break
            }
            
            break
//        case 1:
//            cell.addSubview(nameInput)
//            cell.addSubview(phoneInput)
//            let seper = UIView(frame: CGRect(x: 124, y: 0, width: 1, height: 44))
//            seper.backgroundColor = UIColor.lightGray
//            cell.addSubview(seper)
//            break
        case 1: //2:
            cell.addSubview(commentInput)
            break
        case 2: //3:
            let infoLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32 - 96, height: 16))
            infoLabel.font = UIFont.systemFont(ofSize: 14)
            cell.addSubview(infoLabel)
            
            let priceLabel = UILabel(frame: CGRect(x: view.bounds.width - 88, y: 8, width: 80, height: 16))
            priceLabel.font = UIFont.systemFont(ofSize: 14)
            priceLabel.textAlignment = .right
            priceLabel.textColor = UIColor.lightGray
            cell.addSubview(priceLabel)
            
            priceLabel.text = "￥ 0"
            
            
            if indexPath.row/2 < fileInfos!.count{
                let fileItem = fileInfos?.object(at: indexPath.row/2) as! NSDictionary
                if indexPath.row % 2 == 0{
//                    infoLabel.text = fileItem.object(forKey: "file_name") as? String
//                    infoLabel.text = (fileItem.object(forKey: "file") as? FCPrintFile)?.fileName ?? "文件"
                    infoLabel.text = pricesTabel?.object(forKey: "file_name") as? String ?? (fileItem.object(forKey: "file") as? FCPrintFile)?.fileName ?? "文件"
                    priceLabel.alpha = 0
                }else if indexPath.row % 2 == 1{
                    
                    let pageNum = Int(pricesTabel?.object(forKey: "pnum") as? String ?? "") ?? Int((fileItem.object(forKey: "file") as? FCPrintFile)?.filePage ?? "0") ?? 0
                    let quantity = Int(pricesTabel?.object(forKey: "gnum") as? String ?? "") ?? fileItem.object(forKey: "goods_number") as? Int ?? 0
                    
                    infoLabel.text = "\(pageNum)页 x \(quantity)份"
                    
                    let paperType = pricesTabel?.object(forKey: "type") as? String
                    if paperType != nil{
                        infoLabel.text! += " \(paperType!)"
                    }else{
                    
                        let paperOption = fileItem.object(forKey: "paperOption") as? FCPrintPaperType ?? .blackWhiteSingle
                    
                    
//                        var price:String? = "0"
                        switch paperOption{
                        case .blackWhiteSingle:
                            infoLabel.text! += " 单面 黑白"
//                            price = pricesTabel?.object(forKey: "bsingle") as? String
                            break
                        case .blackWhiteDouble:
                            infoLabel.text! += " 双面 黑白"
//                            price = pricesTabel?.object(forKey: "bdouble") as? String
                            break
                        case .colorSingle:
                            infoLabel.text! += " 单面 彩色"
//                            price = pricesTabel?.object(forKey: "csingle") as? String
                            break
                        case .colorDouble:
                            infoLabel.text! += " 双面 彩色"
//                            price = pricesTabel?.object(forKey: "cdouble") as? String
                            break
                        }
                    }
                
                    
//                    let goodNum = fileItem.object(forKey: "goods_number") as? Int ?? 0
//                    let thisPrice = (Double(price ?? "0") ?? 0.0)*(Double(pageNum))*(Double(goodNum))
//                    if price != nil{
//                        priceLabel.text = "￥ \(String(format: "%.2lf", thisPrice))"
//                    }else{
//                        priceLabel.text = "缺货"
//                    }
                    priceLabel.text = "￥ \(pricesTabel?.object(forKey: "total_price") as? String ?? "缺货")"
                    
                    /*
                    if duplex == 1 && bwOption == 1{
                        infoLabel.text! += " 单面 黑白"
                        var single: Double?
                        let singleStr = pricesTabel.object(forKey: "1")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 1 && bwOption == 2{
                        infoLabel.text! += " 单面 彩色"
                        var single: Double?
                        let singleStr = pricesTabel.object(forKey: "3")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 2 && bwOption == 1{
                        infoLabel.text! += " 双面 黑白"
                        var single: Double?
                        let singleStr = pricesTabel.object(forKey: "2")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 2 && bwOption == 2{
                        infoLabel.text! += " 双面 彩色"
                        var single: Double?
                        let singleStr = pricesTabel.object(forKey: "4")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }*/
                    
                    infoLabel.center.x += 16
                    
                }
                
                
                
            }else{
                if indexPath.row == fileInfos!.count*2 {
                    infoLabel.text = "某种优惠"
                    priceLabel.text = "- ￥ 0"
                    
                    
                }else if indexPath.row == fileInfos!.count*2 + 1{
                    infoLabel.text = "某种优惠"
                    priceLabel.text = "- ￥ 0"
                }
                
            }
            
            break
        default:
            break
        }
        
        
        return cell
    }
    
    func nextStep(){
        
//        if nameInput.text == "" {
//            let alert = UIAlertController(title: "请填写您的姓名", message: nil, preferredStyle: .alert)
//            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in
//                self.nameInput.becomeFirstResponder()
//            }))
//            present(alert, animated: true, completion: nil)
//            return
//        }
//        
//        if phoneInput.text == "" {
//            let alert = UIAlertController(title: "请填写您的联系电话", message: nil, preferredStyle: .alert)
//            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in
//                self.phoneInput.becomeFirstResponder()
//            }))
//            present(alert, animated: true, completion: nil)
//            return
//        }
        
        if hasUnsupportedItems{
            let alert = UIAlertController(title: "商家不支持商品", message: "请返回上一步选择其他商家，或更改文件的打印选项", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
//            if Int(totalPrice*100) != 0{
//                let alert = UIAlertController(title: "商家不支持部分商品", message: "要继续，系统将自动忽略不支持的商品", preferredStyle: .alert)
//                alert.addAction(UIAlertAction(title: "继续", style: .destructive, handler: { (action) in
//                    self.placeOrder()
//                }))
//                alert.addAction(UIAlertAction(title: "返回", style: .cancel, handler: nil))
//                present(alert, animated: true, completion: nil)
//            }else{
//                
//            }
            
        }else{
            placeOrder()
        }
        
        
        
        /*
        if Int(totalPrice*100) != 0{
            print("在此进行提交订单操作")
            spinner.alpha = 1
            submitBtn.isEnabled = false
            submitBtn.backgroundColor = UIColor.gray
            
            let jsonDic = NSMutableDictionary()
            jsonDic.setValue("alipay", forKey: "payMethod")
            
            let shop = shopInfos!//.object(at: 0) as! NSDictionary
            var bid = shop.object(forKey: "id") as? Int
            if bid == nil{
                bid = Int(shop.object(forKey: "id") as! String)
            }
            if bid != nil{
                jsonDic.setValue(bid!, forKey: "bid")
            }
            
            
            if commentInput.text != nil {
                jsonDic.setValue(commentInput.text!, forKey: "remark")
            }
            
            jsonDic.setValue(String(format: "%.2lf", totalPrice), forKey: "totalPrice")
            
            jsonDic.setValue(nameInput.text!, forKey: "name")
            jsonDic.setValue(phoneInput.text!, forKey: "phone")
            UserDefaults.standard.setValue(nameInput.text!, forKey: "info_name")
            UserDefaults.standard.setValue(phoneInput.text!, forKey: "info_phone")
            
            let files = NSMutableArray()
            for f in fileInfos{
                let fileJson = NSMutableDictionary()
                let fileItem = f as! NSDictionary
                let quantity = fileItem.object(forKey: "goods_number") as! Int
                
                let bwOption = fileItem.object(forKey: "black_white_color") as! Int
                let duplex = fileItem.object(forKey: "single_double") as! Int
                
                let fileID = fileItem.object(forKey: "file_id") as! String
                
                fileJson.setValue(fileID, forKey: "file_id")
                fileJson.setValue(quantity, forKey: "goods_number")
                fileJson.setValue(bwOption, forKey: "paper_type")
                fileJson.setValue(duplex, forKey: "single_double")
                files.add(fileJson)
            }
            
            jsonDic.setValue(files, forKey: "fileInfos")
            
            let jsonData = try? JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
            if jsonData != nil {
                print(String(data: jsonData!, encoding: String.Encoding.utf8) ?? "json nil")
                var postResq = URLRequest(url: URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
                postResq.httpMethod = "POST"
                let postData = NSMutableData()
                postData.append("act=submitOrder&json=".data(using: String.Encoding.utf8)!)
                postData.append(jsonData!)
                postResq.httpBody = postData as Data
                
                URLSession.shared.dataTask(with: postResq, completionHandler: { (data:Data?, resq:URLResponse?, err:Error?) in
                    var failed = true
                    var errMsg: String?
                    if err == nil {
                        if data != nil{
                            print(String(data: data!, encoding: String.Encoding.utf8) ?? "data nil")
                            let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                            if jsonObj != nil{
                                let jsonDic = jsonObj as! NSDictionary
                                let reCode = jsonDic.object(forKey: "code") as? Int
                                if reCode == 200{
                                    failed = false
                                    UserDefaults.standard.set(true, forKey: "orderListRefreshRequire")
                                    DispatchQueue.main.async(execute: {
                                        let payVC = PayViewController(amount: self.totalPrice)
                                        payVC.delegate = self
                                        self.present(payVC, animated: true, completion: nil)
                                        
                                    })
                                }else{
                                    errMsg = jsonDic.object(forKey: "message") as? String
                                }
                            }
                        }
                    }
                    
                    if failed{
                        DispatchQueue.main.async(execute: {
                            self.spinner.alpha = 0
                            self.submitBtn.isEnabled = true
                            self.submitBtn.backgroundColor = UIColor.orange
//                            UIAlertView(title: "提交失败", message: errMsg, delegate: nil, cancelButtonTitle: "OK").show()
                            let alert = UIAlertController(title: "提交失败", message: errMsg, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            self.present(alert, animated: true, completion: nil)
                            
                        })
                    }
                    
                }).resume()
            }*/
            
            /*
             //MAR: 写死计时演示
             if #available(iOS 10.0, *) {
             NSTimer.scheduledTimerWithTimeInterval(1, repeats: false) { (timer) in
             
             let payVC = PayViewController(amount: 1.0)
             payVC.delegate = self
             self.presentViewController(payVC, animated: true, completion: nil)
             }
             } else {
             let payVC = PayViewController(amount: 1.0)
             payVC.delegate = self
             self.presentViewController(payVC, animated: true, completion: nil)
             }
         
        }*/
        
        /*else{
         
            let hintToast = UILabel(frame: CGRect(x: 32, y: view.bounds.height - 112, width: view.bounds.width-64, height: 48))
            hintToast.backgroundColor = UIColor(white: 0, alpha: 0.6)
            hintToast.layer.cornerRadius = 8
            hintToast.layer.masksToBounds = true
            hintToast.text = "存在商家不支持的商品，请返回上一步，选择其他商家，或者调整商品属性。"
            hintToast.numberOfLines = 2
            hintToast.font = UIFont.systemFont(ofSize: 14)
            hintToast.textColor = UIColor.white
            view.addSubview(hintToast)
            
            hintToast.alpha = 0
            UIView.animate(withDuration: 0.3, animations: {
                hintToast.alpha = 1
            }, completion: { (finished) in
                UIView.animate(withDuration: 0.3, delay: 2, options: .curveLinear, animations: {
                    hintToast.alpha = 0
                }, completion: nil)
            })
         
            
        }*/
        
        
    }
    
    func placeOrder(){
        if Int(totalPrice*100) != 0{
            print("提交订单")
            UserDefaults.standard.set(nameInput.text ?? "", forKey: "info_name")
            UserDefaults.standard.set(phoneInput.text ?? "", forKey: "info_phone")
            
            let oid = pricesTabel?.object(forKey: "or_num") as? String ?? ""
            
            
            var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=addOrder")!)
            req.httpMethod = "POST"
            req.httpBody = "or_num=\(oid)&postMethod=1&payMethod=alipay&remark=\(commentInput.text ?? "")".data(using: .utf8)
            
            spinner.alpha = 1
            
            URLSession.shared.dataTask(with: req, completionHandler: { (data, _, err) in
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    let reJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let reCode = reJson?.object(forKey: "code") as? Int
                    if reCode == 200{
                        DispatchQueue.main.async {
                            self.payView.openView(String(format: "%0.2lf", self.totalPrice), orderID: oid)
                        }
                    }else{
                        let msg = reJson?.object(forKey: "message") as? String
                        let alert = UIAlertController(title: "请求出错", message: msg, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                            
                            self.spinner.alpha = 0
                        }
                    }
                }catch let ex{
                    self.spinner.alpha = 0
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(ex)
                }
            }).resume()
        }
    }
    
    func placeOrderOld(){
        if Int(totalPrice*100) != 0{
            print("提交订单")
            UserDefaults.standard.set(nameInput.text ?? "", forKey: "info_name")
            UserDefaults.standard.set(phoneInput.text ?? "", forKey: "info_phone")
            /*
             name 姓名
             phone
             totalPrice 1.0
             postMethod 1
             payMethod alipay
             remark 备注
             mer_code 商家代码
             
             fileInfos:
             file_code 文件id
             bsingle 1
             bdouble
             csingle
             cdouble
             goods_number 
             goods_price
             */
            var jsonObj:[String: Any] = [:]
            jsonObj["name"] = nameInput.text ?? ""
            jsonObj["phone"] = phoneInput.text ?? ""
            jsonObj["totalPrice"] = String(format: "%0.2lf", totalPrice)
            jsonObj["postMethod"] = "1"
            jsonObj["payMethod"] = "alipay"
            jsonObj["remark"] = commentInput.text ?? ""
            jsonObj["mer_code"] = shopInfos.object(forKey: "code") as? String ?? ""
            
            var files:[[String: Any]] = []
            for f in self.fileInfos{
                let fileItem = f as? NSDictionary
                
                var fileObj:[String: Any] = [:]
                //["file": printView.file!, "paperOption": printView.paperOption, "goods_number":printView.quantity]
                fileObj["file_code"] = (fileItem?.object(forKey: "file") as? FCPrintFile)?.fileID ?? ""
                fileObj["goods_number"] = "\(fileItem?.object(forKey: "goods_number") as? Int ?? 0)"
                
                let printType = fileItem?.object(forKey: "paperOption") as? FCPrintPaperType ?? .blackWhiteSingle
                
                var paperOption = "bsingle"
                switch printType {
                case .blackWhiteSingle:
                    paperOption = "bsingle"
                    break
                case .blackWhiteDouble:
                    paperOption = "bdouble"
                    break
                case .colorSingle:
                    paperOption = "csingle"
                    break
                case .colorDouble:
                    paperOption = "cdouble"
                    break
                }
                fileObj[paperOption] = "1"
                
                fileObj["goods_price"] = pricesTabel?.object(forKey: paperOption) as? String ?? "0.0"
                
                files.append(fileObj)
            }
            jsonObj["fileInfos"] = files
            
            do{
                let jsonData = try JSONSerialization.data(withJSONObject: jsonObj, options: .prettyPrinted)
                print(String(data: jsonData, encoding: .utf8) ?? "json nil")
                
                var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=addOrder")!)
                resq.httpMethod = "POST"
                resq.httpBody = "json=".data(using: .utf8)
                resq.httpBody?.append(jsonData)
                spinner.alpha = 1
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                    do{
                        if er != nil{
                            throw er!
                        }
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        let reJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let reJsonData = reJson?.object(forKey: "data") as? NSDictionary
                        //                        let reCode = reJson?.object(forKey: "code") as? Int
                        
                        let orderID = reJsonData?.object(forKey: "or_num") as? String
                        
                        if orderID != nil{
                            DispatchQueue.main.async {
                                self.payView.openView(String(format: "%0.2lf", self.totalPrice), orderID: orderID)
                            }
                        }else{
                            let msg = reJson?.object(forKey: "message") as? String
                            let alert = UIAlertController(title: "请求出错", message: msg, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                                
                                self.spinner.alpha = 0
                            }
                        }
                        
                    }catch let exx{
                        self.spinner.alpha = 0
                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        print(exx)
                    }
                }).resume()
                
            }catch let ex{
                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                print(ex)
                
            }
        }
    }
    
    func payView(_ payView: PayView, didCancelPay msg: Any?) ->Bool {
        
        let alert = UIAlertController(title: "退出支付?", message: "请到‘我的订单’中进行支付", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "退出", style: .destructive, handler: { (action) in
            if self.step0VC != nil{
                _ = self.navigationController?.popToViewController(self.step0VC!, animated: true)
            }else{
                _ = self.navigationController?.popToRootViewController(animated: true)
            }
        }))
        alert.addAction(UIAlertAction(title: "不退出", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
        
        return false
    }
    
    func payView(_ payView: PayView, didSuccessPay data: Any?) {
        if self.step0VC != nil{
            _ = self.navigationController?.popToViewController(self.step0VC!, animated: true)
        }else{
            _ = self.navigationController?.popToRootViewController(animated: true)
        }
    }
    
//    func didFinishedPay(_ result: Bool) {
//        if step0VC != nil{
//            _ = navigationController?.popToViewController(step0VC!, animated: true)
//        }else{
//            _ = navigationController?.popToRootViewController(animated: true)
//        }
//    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func textFieldScrollUp(_ textField: UITextField) {
        // MARK: 输入框被键盘遮盖时往上移动
        if textField.tag == commentInput.tag{
            var height = 108 + shopDescriptionHeight // 108->124
            
            height = height - view.bounds.height/2 + 128
            if tableView.contentOffset.y < height{
                tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
            }
        }else if textField.tag == phoneInput.tag || textField.tag == nameInput.tag {
            var height = 108 + shopDescriptionHeight
            
            height = height - view.bounds.height/2 + 128
            if tableView.contentOffset.y < height{
                tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
            }
        }
        
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
